package org.hgvc.webapp.ets.jsf.beans.mastersetup;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.faces.component.UIParameter;
import javax.faces.event.ActionEvent;

import org.hgvc.webapp.ets.bo.Agent;
import org.hgvc.webapp.ets.bo.Calendar;
import org.hgvc.webapp.ets.constant.CommonConstant;
import org.hgvc.webapp.ets.spring.service.MasterSetupService;
import org.jocsb.base.AbstractBean;
import org.jocsb.base.exception.BaseException;


public class CalendarBean extends AbstractBean {
	public static final String BEAN_NAME="calendarBean";
	private MasterSetupService service;
	private List<Calendar> calendarList;
	private Calendar calendar;
	public static final String NAV_LIST_CALENDAR="listCalendar";
	public static final String NAV_ADD_CALENDAR="addCalendar";
	public static final String NAV_EDIT_CALENDAR="editCalendar";
	 
	public MasterSetupService getService() {
		return service;
	}
	public void setService(MasterSetupService service) {
		this.service = service;
	}
	
	public Calendar getCalendar() {
		return calendar;
	}
	public void setCalendar(Calendar calendar) {
		this.calendar = calendar;
	}
	public List<Calendar> getCalendarList() {
		try{
			calendarList = service.getCalendarList();
		}catch(BaseException ex){
			ex.printStackTrace();
			initErrorBean(ex);
		}
		return calendarList;
	}
	public void setCalendarList(List<Calendar> calendarList) {
		this.calendarList = calendarList;
	}
	
	public String navCreationAction(){
		calendar = new Calendar();
		return NAV_ADD_CALENDAR;
	}
	
	public String createAction(){
		try{
			calendar.setCreatedBy(getThisUser());
			calendar.setCreatedDate(new Date());
			calendar.setIsDeleted(CommonConstant.NOT_DELETED);
			service.saveCalendar(calendar);
			return NAV_LIST_CALENDAR;
		}catch(BaseException ex){
			ex.printStackTrace();
			initErrorBean(ex);
		}
		return NAV_ADD_CALENDAR;
	}
	
	public void editListener(ActionEvent actionEvent){
		calendar = null;
		UIParameter parameter = (UIParameter)actionEvent.getComponent().findComponent("calendarId");
		String calendarId = (String)parameter.getValue();
		for(Calendar c:calendarList){
			if(c.getCalendarId().equalsIgnoreCase(calendarId)){
				calendar = c;
				break;
			}
		}
	}
	
	public String navEditAction(){
		return NAV_EDIT_CALENDAR;
	}
	
	public String editAction(){
		try{
			calendar.setModifiedBy(getThisUser());
			calendar.setModifiedDate(new Date());
			service.updateCalendar(calendar);
			return NAV_LIST_CALENDAR;
		}catch(BaseException ex){
			ex.printStackTrace();
			initErrorBean(ex);
		}
		
		return NAV_EDIT_CALENDAR;
	}
	
	public String deleteAction(){
		try{
			List<Calendar> deleteList = new ArrayList<Calendar>();
			for(Calendar c:calendarList){
				if(c.isMarkAsAction()){
					deleteList.add(c);
				}
			}
			service.deleteCalendar(deleteList);
		}catch(BaseException ex){
			ex.printStackTrace();
			initErrorBean(ex);
		}
		return NAV_LIST_CALENDAR;
	}
	
}
